package ca.paulshin.yunatube.youtube;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static ca.paulshin.yunatube.database.YuNaTubeSqliteDatabase.getInstance;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import ca.paulshin.yunatube.R;
import ca.paulshin.yunatube.YunaTubeApplication;
import ca.paulshin.yunatube.common.Constants;
import ca.paulshin.yunatube.common.Preference;
import ca.paulshin.yunatube.common.Utils;
import ca.paulshin.yunatube.main.MainActivity;
import ca.paulshin.yunatube.services.GCMIntentService;
import ca.paulshin.yunatube.services.broadcast.DataChangeReceiver;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;

public class YouTubeActivity extends YouTubeFailureRecoveryActivity implements YouTubePlayer.OnFullscreenListener, OnClickListener {
	private static final int PORTRAIT_ORIENTATION = Build.VERSION.SDK_INT < 9 ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;

	public static final String EXTRA_YOUTUBE_CLIPSET = "extra_youtube_clipset";
	public static final String EXTRA_MYCLIP_SAVE = "extra_myclip_save";
	
	private static final String YOUTUBE_REPORT_WARNING_1 = "youtube_report_warning_1";
	private static final String YOUTUBE_REPORT_WARNING_2 = "youtube_report_warning_2";
	
	private String youtubeCategory, youtubeTitle, youtubeUrl;
	
	private ImageView myClips;
	
	private boolean fullscreen, isSaved;
	private YouTubePlayerView playerView;

	private YouTubeCommentListView listView;
	private TextView emptyView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        
		setContentView(R.layout.youtube);
		
		// Set Youtube Details
		String[] clipSet = getIntent().getStringArrayExtra(EXTRA_YOUTUBE_CLIPSET);
		youtubeCategory = clipSet[0];
		youtubeTitle = clipSet[1];
		youtubeUrl = clipSet[2];
		
		emptyView = (TextView)findViewById(R.id.empty);
		playerView = (YouTubePlayerView) findViewById(R.id.player);
		myClips = (ImageView) findViewById(R.id.youtube_add_to_myclips);
		
		View footerView = ((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.item_footer_to_yuna, null, false);
		listView = (YouTubeCommentListView)findViewById(android.R.id.list);
		listView.init(footerView);
		listView.setDivider(null);
		listView.setDividerHeight(0);
		listView.setEmptyView(emptyView);
		listView.setYoutubeUrl(youtubeUrl);
		listView.load();

		// Report warning
		if (!Preference.contains(YOUTUBE_REPORT_WARNING_2)) {
			Preference.put(YOUTUBE_REPORT_WARNING_2, 1);
			Utils.showToast(YouTubeActivity.this, R.string.youtube_report_warning, false);
		}
		
		TextView category = (TextView) findViewById(R.id.youtube_category);
		if (youtubeCategory != null)
			category.setText(youtubeCategory);
		else {
			myClips.setVisibility(View.GONE);
			category.setVisibility(View.GONE);
		}
		
		TextView title = (TextView) findViewById(R.id.youtube_title);
		title.setText(youtubeTitle);
		
		playerView.initialize(Constants.YOUTUBE_DEVELOPER_KEY, this);
		
		// Customize ActionBar for lower version OS
		if (Build.VERSION_CODES.HONEYCOMB <= Build.VERSION.SDK_INT) {
			ActionBar actionBar = getActionBar();
			if (actionBar != null) {
				actionBar.hide();
				BitmapDrawable bg = (BitmapDrawable) getResources().getDrawable(R.drawable.actionbar_bg);
				bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
				actionBar.setBackgroundDrawable(bg);
			}
		}

		// Check if this is already in myClips
		resetSaveButtonState();

		// Set Button listeners
		myClips.setOnClickListener(this);
		
		ImageView webview = (ImageView) findViewById(R.id.youtube_webview);
		webview.setOnClickListener(this);
		
		ImageView comment = (ImageView) findViewById(R.id.youtube_comment);
		comment.setOnClickListener(this);

		ImageView share = (ImageView) findViewById(R.id.youtube_share);
		share.setOnClickListener(this);

		ImageView report = (ImageView) findViewById(R.id.youtube_report);
		report.setOnClickListener(this);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		mNotificationManager.cancel(GCMIntentService.NOTIFICATION_ID);
	}

	/**
	 * YouTube API
	 */
	@Override
	public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
		player.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CUSTOM_LAYOUT);
		player.setOnFullscreenListener(this);
		if (!wasRestored) {
			player.loadVideo(youtubeUrl);
		}

		int controlFlags = player.getFullscreenControlFlags();
		setRequestedOrientation(PORTRAIT_ORIENTATION);
		controlFlags |= YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE;
		player.setFullscreenControlFlags(controlFlags);
	}

	@Override
	protected YouTubePlayer.Provider getYouTubePlayerProvider() {
		return playerView;
	}

	@Override
	public void onFullscreen(boolean isFullscreen) {
		fullscreen = isFullscreen;
		doLayout();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		fullscreen = (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE);
		doLayout();
	}

	private void doLayout() {
		LinearLayout.LayoutParams playerParams = (LinearLayout.LayoutParams) playerView.getLayoutParams();
		if (fullscreen) {
			// When in fullscreen, the visibility of all other views than the player should be set to
			// GONE and the player should be laid out across the whole screen.
			playerParams.width = LayoutParams.MATCH_PARENT;
			playerParams.height = LayoutParams.MATCH_PARENT;
		} else {
			ViewGroup.LayoutParams otherViewsParams = listView.getLayoutParams();
			playerParams.width = otherViewsParams.width = MATCH_PARENT;
			playerParams.height = WRAP_CONTENT;
			playerParams.weight = 0;
			otherViewsParams.height = WRAP_CONTENT;
		}
	}

	private void resetSaveButtonState() {
		isSaved = getInstance().isInMyClips(youtubeUrl);
		myClips.setImageResource(isSaved ? R.drawable.ic_star_full : R.drawable.ic_star_empty);
	}
	
	@Override
	public void onStart() {
		super.onStart();
		EasyTracker.getInstance().activityStart(this);
	}

	@Override
	public void onStop() {
		super.onStop();
		EasyTracker.getInstance().activityStop(this);
	}
	
	@Override
	public void finish() {
		super.finish();
		overridePendingTransition(R.anim.open_main, R.anim.close_next);
	}
	
	private void openCommentDialog() {
		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
	    final EditText input = new EditText(this);
	    input.setFilters(new InputFilter[] { new InputFilter.LengthFilter(140) });
	    input.setLines(4);
	    input.setHint(R.string.to_yuna_hint);
	    alert.setTitle(R.string.youtube_comment);
	    alert.setView(input);
	    alert.setCancelable(false);
	    alert.setPositiveButton(R.string.dialog_send, new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int whichButton) {
	            String value = input.getText().toString().trim();
	            if (TextUtils.isEmpty(value)) {
	            	Utils.showToast(YouTubeActivity.this, R.string.enter_data);
	            }
	            else {
	            	String userName = Preference.getString(MainActivity.NICKNAME);
	            	userName = TextUtils.isEmpty(userName) ? getString(R.string.nickname_noname) : userName;
	            	String deviceId = Secure.getString(YouTubeActivity.this.getContentResolver(), Secure.ANDROID_ID);
	            	listView.update(youtubeUrl, userName, value, String.valueOf(System.currentTimeMillis() / 1000), deviceId);
	            }
	        }
	    });

	    alert.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int whichButton) {
	            dialog.cancel();
	        }
	    });
	    alert.show();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.youtube_add_to_myclips:
			if (isSaved) {
				if (getInstance().removeMyClip(youtubeUrl)) {
					// Signal myClip change
					Intent finishIntent = new Intent();
					finishIntent.setAction(DataChangeReceiver.ACTION);					
					finishIntent.putExtra(EXTRA_MYCLIP_SAVE, true);
					YunaTubeApplication.broadcast.sendBroadcast(finishIntent);
					
					Utils.showToast(YouTubeActivity.this, R.string.cmenu_pop_remove_successful);
					resetSaveButtonState();
				}
			} else {
				long id = getInstance().insertToMyClips(youtubeCategory, youtubeTitle, youtubeUrl);
				if (id > 0) {
					// Signal myClip change
					Intent finishIntent = new Intent();
					finishIntent.setAction(DataChangeReceiver.ACTION);					
					finishIntent.putExtra(EXTRA_MYCLIP_SAVE, true);
					YunaTubeApplication.broadcast.sendBroadcast(finishIntent);
					
					Utils.showToast(YouTubeActivity.this, youtubeTitle + " " + getResources().getString(R.string.cmenu_myclips_add_successful));
					resetSaveButtonState();
				} else
					Utils.showToast(YouTubeActivity.this, "ERROR: " + youtubeTitle + " " + getResources().getString(R.string.cmenu_myclips_add_failure));
			}
			break;
			
		case R.id.youtube_webview:
			String url = "http://www.youtube.com/v/" + youtubeUrl;
			Intent i = new Intent(Intent.ACTION_VIEW);
			i.setData(Uri.parse(url));
			startActivity(i);
			break;
			
		case R.id.youtube_comment:
			if (!listView.isBusy)
				openCommentDialog();
			else
				Utils.showToast(YouTubeActivity.this, R.string.youtube_wait);
			break;
			
		case R.id.youtube_share:
			Utils.share(YouTubeActivity.this, getString(R.string.youtube_share_title), getString(R.string.youtube_share_subject), getString(R.string.youtube_share_text) + " " + youtubeTitle
					+ ": http://youtu.be/" + youtubeUrl + " " + getString(R.string.youtube_share_via));
			break;
			
		case R.id.youtube_report:
			if (!Preference.contains(YOUTUBE_REPORT_WARNING_1)) {
				Preference.put(YOUTUBE_REPORT_WARNING_1, 1);
				Utils.showToast(YouTubeActivity.this, R.string.youtube_report_warning, false);
			}
			Dialog reportDialog = new ReportDialog(YouTubeActivity.this, youtubeTitle, youtubeUrl);
			reportDialog.show();
			break;
		}
	}
}
